<template>
  <div class="consultRoom-page">
   <div class="top-bar">
        <div class="top-bar-left">
            <img src="@/assets/back.png" alt="" class="back-img" 
            @click="onClickLeft" >
        </div>
        <div class="top-bar-center">
            <div class="title">
                {{consultantData.name}}
            </div>
        </div>
        <div class="top-bar-right">
             <img :src="consultantData.avatar" alt="" class="avatar">
        </div>
   </div>  
   <van-list>
      <van-cell v-for="(message, index) in messages" :key="message.id"
    :class="message.sender_type === 'user' ? 'msg-right' : 'msg-left'">
      <div class="msg-box">
        <div class="msg-box_lf">
           <img  :src="message.sender_type==='user'? user_avatar:consultantData.avatar " alt="">
        </div>
        <div class="msg-box_rg">
           <div class="chat-time">{{ message.send_time }}</div>
           <p class="message">{{ message.content }}</p>
        </div>
      </div>
     </van-cell>
  </van-list>
  <div class="chat-input">
    <div class="input-left">
      <gh-icon class="voice-o" name="consult-voice-o" @click="switchInputType('voice')" />
    </div>
    <div class="input-center">
      <van-field
        v-model="message"
        placeholder="Type your message..."
        autosize
        focused
        @focus="adjustInputPosition"
        @keydown.enter="sendMessage"
      />
    </div>
    <div class="input-right">
      <van-icon class="smile" name="smile-o" @click="switchInputType('emoji')" />
      <van-icon name="plus" @click="switchInputType('attachment')" />
    </div>
  </div>
  </div>
</template>

<script setup>
import {ref,reactive,onBeforeMount,computed,onMounted,watch,onBeforeUnmount} from "vue"
import { Toast, Dialog } from 'vant';
import {getConsultantInfoByAppointment_id,getuserIdByappointment_id} from '@/services/consult'
import {fetchChatMessages} from '@/services/others'
import { getImage} from '@/services/user'
import 'vant/es/toast/style'
import{useRouter,useRoute}from 'vue-router'
import { io } from 'socket.io-client'
const router =useRouter();  
const route =useRoute()
//头部导航栏左边箭头点击返回上一页
const onClickLeft=()=>{
if(history.state){
    //存在回跳地址就返回
router.back()
}else{
    //不存在返回首页
    router.push('/')

}
}
//输入框消息响应式变量
const message=ref('')
//聊天记录消息响应式变量
const messages=ref([])
//咨询师信息响应式变量
const consultantData=ref('')
//用户id响应式变量
const user_id=ref('')
//用户信息响应式变量
const personalInfo=ref('')

let isKeyboardShown = false;
onMounted(async() => {
      socket.on("connect", () => {
        //  console.log(socket.id); 
      });
      socket.on('receiveChatMsg', (data) => {
        console.log('收到的消息：',data.content)
        messages.value.push(data);
      });
    });
    let connected = false
    //用户照片响应式变量
    const user_avatar=ref('')
    //用户角色响应式变量
const roleData=ref('')
onBeforeMount(async()=>{
    const role=JSON.parse(localStorage.getItem('gh-user')).user.userData.role
    roleData.value=role
    const avatar =JSON.parse(localStorage.getItem('gh-user')).user.userData.avatar
    // console.log(roleData.value)
    const appointment_id=route.params.id
    //根据预约号id来查询对应咨询师信息和用户信息
    const res=await getConsultantInfoByAppointment_id(appointment_id)
    const userid=await getuserIdByappointment_id(appointment_id)
    user_id.value=userid.data.user_id
    consultantData.value=res.data
    const avararData=await getImage(avatar)
    let imageData
   for(let i = 0; i < avararData.data.base64Chunks.length; i++) {
    // 合并分块 Base64 数据
   const base64Data = avararData.data.base64Chunks.join('');
    imageData = `data:image/jpeg;base64,${base64Data}`;
}
    user_avatar.value=imageData
    if ( user_id&& consultantData.value.id) {
      socket.emit('join', { senderId: user_id.value, receiverId: consultantData.value.id ,role:roleData.value});
      connected = true;
     }
     const messagesData=await fetchChatMessages(user_id.value,consultantData.value.id)
     messages.value=messagesData.data
})
//离开组件触发
onBeforeUnmount(()=>{
    socket.disconnect()
})

//调整输入框位置
const adjustInputPosition = () => {
  if (isKeyboardShown) {
    isKeyboardShown = false;
    return;
  }

  const chatInput = document.querySelector('.chat-input');
  if (!chatInput) return;
  
  let clientHeight = window.innerHeight;
  let inputPosition = chatInput.getBoundingClientRect().top;
  const inputHeight = chatInput.clientHeight;
  const keyboardHeight = clientHeight - inputPosition - inputHeight;

  if (keyboardHeight < 0) {
    chatInput.style.transform = `translateY(${keyboardHeight}px)`;
    isKeyboardShown = true;
  }
};

const switchInputType = (type) => {
  switch (type) {
    case 'voice':
     console.log('说话')
      break;
    case 'emoji': 
      console.log('表情包')
      break;
    case 'attachment':
      console.log('其他')
      break;
    default:
      break;
  }
};
const socket = io('http://localhost:8888');
//回车发送消息
const sendMessage = () => {
  if (message.value.trim() !== '') {
    console.log('发送的消息:', message.value);
     // 获取当前本地时间
     const currentDate = new Date()
    // 格式化为数据库datetime格式的字符串
     const currentTime = `${currentDate.getFullYear()}-${String(currentDate.getMonth() + 1).padStart(2, '0')}-${String(currentDate.getDate()).padStart(2, '0')} ${String(currentDate.getHours()).padStart(2, '0')}:${String(currentDate.getMinutes()).padStart(2, '0')}:${String(currentDate.getSeconds()).padStart(2, '0')}`;
    //  console.log(currentTime)
    const data={
        'content':message.value,
        'senderId':user_id.value,
        'receiverId':consultantData.value.id,
         'sendTime':currentTime,
         'sender_type':'user',
         'role':roleData.value
    }
    socket.emit('chatMessage',data)
    messages.value.push(data)
    message.value = '';
  }
};

</script>

<style lang="scss" scoped>
.consultRoom-page{
    width: 100%;
    height: 100%;
   .top-bar{
    position: fixed;
    z-index: 99;
    top: 0;
    left: 0;
    padding: 0 12px;
    width: 100%;
    height: 50px;
    background-color: #f5f5f5;
    text-align: center;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid var(--gh-line);
    .top-bar-left{
        height: 35px;
        width: 35px;
       .back-img{
         display: block;
         height: 100%;
         height: 100%;
       }
    }
    .top-bar-center{
        flex: 1;
        .title{
            font-size: 17px;
            font-family: '黑体';
        }
    }
    .top-bar-right{
        width: 40px;
        height: 40px;
        .avatar{
         display: flex;
         height: 100%;
         width: 100%;
         border-radius: 8px;
        }
    }
   }
   .van-list{
      margin: 40px 0;
      width: 100%;
      .msg-left{
        padding: 10px 5px;
        .msg-box{
            display: flex;
            .msg-box_lf{
                width: 45px;
                height: 45px;
              img{
                  display: block;
                  height: 100%;
                  width: 100%;
                  border-radius: 10px;
                }
             }
             .msg-box_rg{
                margin-left: 10px;
                .chat-time{
                    font-size: 10px;
                    color: var(--gh-text3);
                }
                .message{
                    flex: auto;
                    max-width: 220px;
                    min-height: 30px;
                    padding: 5px 10px;
                    border-radius: 8px;
                    font-size: 14px;
                    font-family: '黑体';
                    background-color: #f5f5f5;
                }
             }
        }
      
      }
       .msg-right{
          padding: 10px 5px;
          .msg-box{
              display: flex;
              flex-direction: row-reverse;
            .msg-box_lf{
                width: 45px;
                height: 45px;
              img{
                  display: block;
                  height: 100%;
                  width: 100%;
                  border-radius: 10px;
              }
             }
             .msg-box_rg{
                margin-right: 10px;
                .chat-time{
                    text-align: right;
                    margin-right: 5px;
                    font-size: 10px;
                    color: var(--gh-text3);
                }
                .message{
                    flex: auto;
                    max-width: 220px;
                    min-height: 30px;
                    padding: 5px 10px;
                    border-radius: 8px;
                    font-size: 14px;
                    font-family: '黑体';
                    background-color: #95EC69;
                }
             }
        }
       }


   }
   .chat-input{
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 9999;
    background-color: #fff;
    padding: 0 16px;
    .input-left{
        font-size: 18px;
        text-align: center;
        display: flex;
        justify-content: center;
    }
    .input-right{
        font-size: 18px;
        .smile{
            margin-right: 8px;
        }
    }
    .input-center{
        flex: 1;
        display: flex;
        justify-content: center;
        .van-field{
            margin: 0;
            width: 100%;
        }
    }
   }


}
</style>
